<template>
    <div>
        <Header/>

        <div class="form-container">
            <el-form ref="userForm" status-icon :model="ruleForm" label-width="80px" :rules="rules" style="width: 80%;">
                <el-form-item label="用户名" prop="loginName" required>
                    <el-input v-model="ruleForm.loginName"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password" required>
                    <el-input v-model="ruleForm.password" type="password"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="checkPass" required>
                    <el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="昵称">
                    <el-input v-model="ruleForm.username"></el-input>
                </el-form-item>
                <el-form-item label="性别" required>
                    <el-radio-group v-model="ruleForm.gender">
                        <el-radio label="男"></el-radio>
                        <el-radio label="女"></el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="出生日期"  required>
                    <el-col :span="11">
                        <el-form-item prop="birthday">
                            <el-date-picker type="date" placeholder="选择日期" v-model="ruleForm.birthday" style="width: 100%;"></el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-form-item>
                <el-form-item>
                    <el-upload
                        action="123"  list-type="picture-card"
                        :http-request="upload"
                        :on-success="handlerUploadSuccess"
                        :show-file-list="false"
                        :on-preview="handlePictureCardPreview"
                        :before-upload="beforeAvatarUpload"
                        :on-remove="handleRemove">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" :src="imageUrl" alt="">
                    </el-dialog>
                </el-form-item>

                <el-form-item label="简介">
                    <el-input type="textarea" v-model="ruleForm.intro" ></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="createAdmin('userForm')">立即创建</el-button>
                    <el-button>取消</el-button>
                </el-form-item>
            </el-form>
        </div>

    </div>
</template>

<script>
    import Header from '@/components/Header'
    import Footer from '@/components/Footer'
    import {createAdmin, isExistsLoginName, uploadImg} from "../../api/getData";
    import dtime from 'time-formater'

    export default {
        name: "Create",
        components: {Header, Footer},
        data(){
            var validateLoginName = async (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('用户名不能为空'));
                }
                // 校验该用户名是否存在
                const isExists = await isExistsLoginName({loginName:value});
                if(isExists.data.data == true){
                    return callback(new Error('用户名已存在'));
                }
            };
            var validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'));
                } else {
                    if (this.ruleForm.checkPass !== '') {
                        this.$refs.userForm.validateField('checkPass');
                    }
                    callback();
                }
            };
            var validatePass2 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.ruleForm.password) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
            return{
                user:{},
                ruleForm: {
                    password: '123',
                    checkPass: '123',
                    loginName: 'admin22', username:'admin22',
                    gender: '男',
                    // birthday: dtime(new Date())
                },
                rules: {
                    loginName:[{ validator: validateLoginName, trigger: 'blur' }],
                    password: [
                        { validator: validatePass, trigger: 'blur' }
                    ],
                    checkPass: [
                        { validator: validatePass2, trigger: 'blur' }
                    ],
                    birthday: [
                        { type: 'date', required: true, message: '请选择时间', trigger: 'change' }
                    ],
                },
                dialogVisible:false,
                dialogImageUrl:'',
                imageUrl:''
            }
        },
        methods:{
            async createAdmin(form){
                this.$refs[form].validate(async (valid) => {
                    if (valid) {
                        var birthday = dtime(this.ruleForm.birthday).format('YYYY/MM/DD')
                        var data = {
                            loginName: this.ruleForm.loginName,
                            username: this.ruleForm.username,
                            password: this.ruleForm.password,
                            gender: this.ruleForm.gender,
                            birthday: birthday,
                            intro: this.ruleForm.intro,
                            token: this.$store.state.token
                        }
                        console.log(data)
                        const res = await createAdmin(data);
                        if(res.data.code == 0){
                            this.$message('注册成功')
                        }
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            handleRemove(file, fileList) {
                console.log(file, fileList);
            },
            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },
            async upload(file) {
                const formData = new FormData();
                formData.append('file', file.file);
                this.$http.post("/api/user/upload/post", formData, {headers:{'Content-Type':'multipart/form-data'}})
                    .then(res=>{
                        this.imageUrl = this.HOST  + res.data.data.imageUrl + "?aa=1";
                        this.$message('头像上传成功');
                    })
            },
            beforeAvatarUpload(file){
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                // if (!isJPG) {
                //     this.$message.error('上传头像图片只能是 JPG 格式!');
                // }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isLt2M;
            },
            handlerUploadSuccess(res, files, fileList){
                console.log(res)
                // this.imageUrl = this.HOST +res.data.imageUrl;
            }
        }
    }
</script>

<style scoped lang="less">
.form-container{
    padding: 20px;
}
    .avatar{
        width: 149px;
        height: 149px;
        float: left;
    }
</style>
